import type { IUserCenterModule } from '../../types/interfaces'
import { Toolbar } from '../../components/toolbar'
import { EventEmitter } from '../../lib/event_emitter'
import { ConfigManager } from '../../module/config_manager'
import { SYMBOLS } from '../../types/interfaces'
import { FeatureToggle } from '../feature_toggle'

export class UtilitySettings implements IUserCenterModule {
  readonly id: string = 'utility-settings'
  readonly name: string = 'UtilitySettings'
  private readonly featureToggle: FeatureToggle // 功能开关
  private readonly eventEmitter: EventEmitter = EventEmitter.getInstance()
  private toolbarInstance: Toolbar | null = null
  private static instance: UtilitySettings

  constructor() {
    this.featureToggle = FeatureToggle.getInstance()
    this.initDomainSpecificFeatures()
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): UtilitySettings {
    if (!UtilitySettings.instance) {
      UtilitySettings.instance = new UtilitySettings()
    }
    return UtilitySettings.instance
  }

  /**
   * 初始化域名特定功能
   */
  private initDomainSpecificFeatures(): void {
    this.featureToggle.registerFeatures(ConfigManager.getInstance().getPlatformModules())
  }

  public generateHTML(): string {
    const enabledCount = this.featureToggle.getEnabledCount()
    const totalCount = this.featureToggle.getTotalCount()

    return `
      <div class="utility-settings">
        <div class="menu-container">
          <div class="status-display">
            <div class="status-badge enabled">
              <span class="status-count">${enabledCount}</span>
              <span class="status-label">已启用</span>
            </div>
            <div class="status-badge total">
              <span class="status-count">${totalCount}</span>
              <span class="status-label">总功能</span>
            </div>
          </div>
          <div class="toolbar-container">
            ${this.getToolbar().render()}
          </div>
        </div>
        ${this.featureToggle.generateHTML()}
      </div>
    `
  }

  private getToolbar(): Toolbar {
    if (!this.toolbarInstance) {
      this.toolbarInstance = this.initToolbar()
    }
    return this.toolbarInstance
  }

  private initToolbar(): Toolbar {
    const menus = [
      {
        id: 'feature-switches-menu',
        icon: SYMBOLS.UI.SETTINGS,
        text: '功能菜单',
        children: [
          { id: 'enable-features', text: '一键开启', icon: SYMBOLS.OTHERS.OPEN, onClick: () => this.featureToggle.enableAll() },
          { id: 'disable-features', text: '一键关闭', icon: SYMBOLS.OTHERS.STOP, onClick: () => this.featureToggle.disableAll() },
          { id: 'reset-features', text: '重置设置', icon: SYMBOLS.STATUS.REFRESH, onClick: () => this.featureToggle.reset() },
        ],
      },
    ]
    return new Toolbar({
      id: 'utility-settings-toolbar',
      menus,
    })
  }

  handleOpen(): void {
    this.featureToggle.handleOpen()
    this.getToolbar().mount($('.utility-settings'))

    // 初始更新显示
    this.updateStatusDisplay()

    // 监听变化自动更新
    this.eventEmitter.on('stats-updated', () => this.updateStatusDisplay())
  }

  destroy(): void {
    // 1. 清理工具栏实例
    if (this.toolbarInstance) {
      this.toolbarInstance.destroy()
      this.toolbarInstance = null
    }

    // 2. 移除事件监听器
    this.eventEmitter.off('stats-updated')

    // 3. 清理子组件
    this.featureToggle.destroy?.()
  }

  /**
   * 更新状态显示
   */
  private updateStatusDisplay(): void {
    const { enabled, total } = this.featureToggle.updateFeatureStats()
    const $container = $('.status-display')

    $('.status-display .enabled .count').text(enabled)
    $('.status-display .total .count').text(total)

    // 清除所有状态类
    $container.removeClass('all-enabled zero-enabled')

    // 设置状态类
    if (enabled === 0) {
      $container.addClass('zero-enabled')
    }
    else if (enabled === total && total > 0) {
      $container.addClass('all-enabled')
    }
  }

  public styles(): string {
    return `
      .utility-settings {
        .menu-container {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 16px;
          margin-bottom: 8px;
        }
        
        .status-display {
          display: flex;
          align-items: center;
          user-select: none !important;
          gap: 12px;
          
          /* 全部启用状态 */
          &.all-enabled {
            .status-badge.enabled {
              background: rgba(23, 162, 184, 0.1);
              border-color: rgba(23, 162, 184, 0.3);
              
              .count {
                color: #17a2b8;
              }
            }
          }
          
          /* 零启用状态 */
          &.zero-enabled {
            .status-badge.enabled {
              background: rgba(220, 53, 69, 0.1);
              border-color: rgba(220, 53, 69, 0.3);
              
              .count {
                color: #dc3545;
              }
            }
          }
          
          /* 默认部分启用状态 */
          &:not(.all-enabled):not(.zero-enabled) {
            .status-badge.enabled {
              background: rgba(40, 167, 69, 0.1);
              border-color: rgba(40, 167, 69, 0.3);
              
              .count {
                color: #28a745;
              }
            }
          }
          
          .status-badge {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 6px 10px;
            border-radius: 8px;
            gap: 5px;
            min-width: 60px;
            
            .status-count {
              font-size: 18px;
              font-weight: bold;
              line-height: 1;
            }
            
            .status-label {
              font-size: 12px;
              opacity: 0.8;
            }
            
            &.enabled, &.total {
              border: 1px solid rgba(108, 117, 125, 0.3);
            }
            
            &.total {
              background: rgba(108, 117, 125, 0.1);
              .count {
                color: #6c757d;
              }
            }
          }
        }
      }
    `
  }
}
